# -*- coding:utf-8 -*-
import flask
import json
import hashlib
import re
from gevent import pywsgi

import requests

# 自己的账号密码
passwordStr = ''

# 禅道地址
base_url = ''

login_url = base_url + '/zentao/user-login.html'

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                         'Chrome/90.0.4430.93 Safari/537.36'}

dynamic_bug_url = base_url + '/zentao/company-dynamic.json'

unclosed_bug_url = base_url + '/zentao/bug-browse-%s-0-unclosed-0--0-100-1.json'

account_data = {
    # 自己的账号
    'account': '',
    'password': '',
    # 抓包看看自己的账号对应的是多少
    'passwordStrength': 1,
    'verifyRand': ''
}


def get_context(url, header):
    return requests.get(url, headers=header)


def post_context_data(url, data, header, request_cookie):
    return requests.post(url, data=data, headers=header, cookies=request_cookie)


def get_cookie(response):
    return requests.utils.dict_from_cookiejar(response.cookies)


def md5_encryption(data):
    md5_data = hashlib.md5()
    md5_data.update(data.encode(encoding='utf-8'))
    return md5_data.hexdigest()


def login_auth():
    login_response = get_context(login_url, headers)
    login_content = login_response.content.decode('utf8')
    # 正则匹配verifyRand
    p = re.compile(r'verifyRand.*value=\'(.*)\'', re.M)
    verifyRand = p.findall(login_content)[0]
    account_data['verifyRand'] = verifyRand
    cookies = get_cookie(login_response)
    account_data['password'] = md5_encryption(md5_encryption(passwordStr) + str(verifyRand))
    post_context_data(login_url, account_data, headers, cookies)
    cookies['windowWidth'] = '1920'
    cookies['windowHeight'] = '1080'
    return cookies


def get_bug_data_json_translate(url, header, login_cookie):
    response = requests.get(url=url, headers=header, cookies=login_cookie)
    dynamic_context = response.content.decode('utf8')
    dynamic_json_data = json.loads(dynamic_context)
    return json.loads(dynamic_json_data['data'])


def get_new_bug_id(login_cookie):
    bugVos = {'dynamicBugVoList': '', 'bugDescribeVoList': ''}
    # 获取动态详情
    dynamic_data = get_bug_data_json_translate(dynamic_bug_url, headers, login_cookie)

    product_ids = set()
    for key in dynamic_data['dateGroups']:
        bugVos['dynamicBugVoList'] = dynamic_data['dateGroups'][key]
        # 遍历动态详情取出其中存在的bug项目
        for item in dynamic_data['dateGroups'][key]:
            p = re.compile(r'\d+')
            product = p.findall(item['product'])
            product_ids.add(product[0])

    bug_describe_data = list()
    for key in product_ids:
        # 遍历bug项目拉取对应的最近100条bug
        bug_describe_data.extend(get_bug_data_json_translate(unclosed_bug_url % key, headers, login_cookie)['bugs'])
    bugVos['bugDescribeVoList'] = bug_describe_data
    return bugVos


def get_user(login_cookie):
    desc = get_bug_data_json_translate(unclosed_bug_url % 1, headers, login_cookie)
    return desc['users']


app = flask.Flask(__name__)


@app.route('/push-bug', methods=['post'])
def push_bugs():
    res = get_new_bug_id(login_auth())
    return json.dumps(res)


@app.route('/push-users', methods=['post'])
def push_users():
    res = get_user(login_auth())
    return json.dumps(res)


if __name__ == '__main__':
    server = pywsgi.WSGIServer(('0.0.0.0', 50000), app)
    server.serve_forever()
